package com.utooo.service.purchase;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.utooo.dao.purchase.HistoryPriceMapper;
import com.utooo.dao.purchase.PriceCenterMapper;
import com.utooo.pojo.domain.purchase.price.HistoryPriceDO;
import com.utooo.pojo.domain.purchase.price.PriceCenterDO;
import com.utooo.pojo.dto.purchase.price.PriceUpdateStatusDto;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

import static com.utooo.constant.Constans.IGNORED_PROPERTIES;

/**
 * @Description: TODO
 * @Author SJD
 * @Date: 2025/4/27 14:34
 * @Copyright: 南京优通信息科技股份有限公司
 */
@Service
@RequiredArgsConstructor
public class PriceCenterServiceImpl  extends ServiceImpl<PriceCenterMapper, PriceCenterDO> implements PriceCenterService{

    private final HistoryPriceMapper historyPriceMapper;
    @Override
    public Boolean updateStatus(PriceUpdateStatusDto param) {
        // 根据ID获取价格中心数据
        PriceCenterDO priceCenterDO = getById(param.getId());

        // 检查priceCenterDO是否为null
        if (priceCenterDO == null) {
            throw new IllegalArgumentException("PriceCenterDO not found for id: " + param.getId());
        }

        // 使用常量表示状态值
        final String STATUS_UPDATED = "2";

        // 获取当前时间戳
        LocalDateTime now = LocalDateTime.now();

        // 更新价格中心状态、失效时间和更新时间
        priceCenterDO.setStatus(STATUS_UPDATED);
        priceCenterDO.setExpirationTime(now);
        priceCenterDO.setUpdateTime(now);

        try {
            // 更新价格中心数据
            updateById(priceCenterDO);

            // 将当前价格中心数据备份到历史价格表中
            HistoryPriceDO historyPriceDO = BeanUtil.copyProperties(priceCenterDO, HistoryPriceDO.class, IGNORED_PROPERTIES);
            historyPriceMapper.insert(historyPriceDO);
        } catch (Exception e) {
            // 处理异常
            throw new RuntimeException("Failed to update price center status", e);
        }
        return Boolean.TRUE;
    }
}
